package com.meilai.project.controller.web.business.sale;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.meilai.project.dto.business.sale.*;
import com.meilai.project.dto.base.ApiResult;
import com.meilai.project.entity.business.saleOrder.BillSaleAppendix;
import com.meilai.project.service.business.sale.BillSaleService;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.vo.business.sale.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author xchen
 * @since 2022-03-19
 */
@Api(value = "销售单controller", tags = "销售单")
@RequestMapping("api/web/bill_sale")
@RestController
@Validated
@Slf4j
public class BillSaleController {

    @Autowired
    private BillSaleService service;

    @GetMapping("media_type_count_amount")
    @ApiOperation("每种媒体类型对应的数量及金额")
    public ApiResult<List<MediaSpecTypeCountAmountVO>> mediaTypeCountAmount(
            @ApiParam("dateRangeId") @RequestParam("dateRangeId") Long dateRangeId
    ) {
        try {
            return ApiResult.ok(service.mediaTypeCountAmount(dateRangeId));
        } catch (Exception e) {
            log.error("", e);
            return ApiResult.err("查询错误，请联系管理员！");
        }
    }

    @GetMapping("list-for-market-by-contract-id")
    @ApiOperation(value = "根据合同id查销售单(For市场单)")
    public ApiResult<List<BillSaleVO>> listForMarketByContractId(
            @Param("contractId") Long contractId,
            @Param("mustIncludeBillSaleId") Long mustIncludeBillSaleId,
            @Param("type") Integer type
    ) {
        List<BillSaleVO> BillSaleVOPage = service.listForMarketByContractId(contractId, mustIncludeBillSaleId, type);
        return ApiResult.ok(BillSaleVOPage);
    }

    @GetMapping("list")
    @ApiOperation(value = "列表分页")
    public ApiResult<Page<BillSaleVO>> list(@ApiParam("form") BillSaleListDTO req) {
        if (req.isManager()) {
            req.setUserId(null);
        } else {
            req.setUserId(ThreadLocalUserUtil.get().getId());
        }
        Page<BillSaleVO> BillSaleVOPage = service.selectPageList(req);
        return ApiResult.ok(BillSaleVOPage);
    }

    @GetMapping("detail")
    @ApiOperation(value = "单据明细")
    public ApiResult<BillSaleVO> detail(
            @ApiParam("id") @RequestParam(value = "id", required = false) Long id) {
        return ApiResult.ok(service.getOneById(id));
    }

    @PostMapping("save")
    @ApiOperation("保存")
    public ApiResult<Boolean> save(@ApiParam("json") @RequestBody BillSaleDTO req) {
        try {
            if (service.save(req)) {
                return ApiResult.ok("新增成功");
            } else {
                return ApiResult.err("新增失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err(e.getMessage());
        }
    }

    @PutMapping("begin")
    @ApiOperation("提交")
    public ApiResult<Boolean> begin(@ApiParam("json") @RequestBody BillSaleDTO req) {
        try {
            if (service.begin(req)) {
                return ApiResult.ok("提交成功");
            } else {
                return ApiResult.err("提交失败");
            }
        } catch (Exception e) {
            return ApiResult.err(e.getMessage());
        }
    }

    @PutMapping("pass")
    @ApiOperation("通过")
    public ApiResult<Boolean> pass(@ApiParam("json") @RequestBody BillSaleCheckDTO req) {
        try {
            if (service.pass(req)) {
                return ApiResult.ok("通过成功");
            } else {
                return ApiResult.err("通过失败");
            }
        } catch (Exception e) {
            log.error("exception", e);
            return ApiResult.err(e.getMessage());
        }
    }

    @PutMapping("return_back")
    @ApiOperation("驳回")
    public ApiResult<Boolean> returnBack(@ApiParam("json") @RequestBody BillSaleCheckDTO req) {
        try {
            if (service.returnBack(req)) {
                return ApiResult.ok("驳回成功");
            } else {
                return ApiResult.err("驳回失败");
            }
        } catch (Exception e) {
            return ApiResult.err(e.getMessage());
        }
    }

    @DeleteMapping("delete")
    @ApiOperation(value = "逻辑删除")
    public ApiResult<Boolean> delete(@RequestParam("id") @ApiParam("id") Long id) {
        try {
            if (service.delete(id)) {
                return ApiResult.ok("删除成功");
            } else {
                return ApiResult.err("删除失败");
            }
        } catch (Exception e) {
            return ApiResult.err(e.getMessage());
        }
    }

    @DeleteMapping("actual_delete")
    @ApiOperation(value = "物理删除")
    public ApiResult<Boolean> actualDelete(@RequestParam("id") @ApiParam("id") Long id) {
        try {
            if (service.actualDelete(id)) {
                return ApiResult.ok("彻底删除成功");
            } else {
                return ApiResult.err("彻底删除失败");
            }
        } catch (Exception e) {
            return ApiResult.err(e.getMessage());
        }
    }


    @GetMapping("dispatch/list")
    @ApiOperation(value = "列表分页 提供给调度查看")
    public ApiResult<Page<BillSaleVO2>> dispatchList(@ApiParam("form") BillSaleListDTO req) {
        Page<BillSaleVO2> BillSaleVOPage = service.dispatchList(req);
        return ApiResult.ok(BillSaleVOPage);
    }


    @PostMapping("confirmMonitor")
    @ApiOperation(value = "确认监播发送")
    public ApiResult<Boolean> confirmMonitor(@RequestParam("id") Long id) {
        return ApiResult.ok(service.confirmMonitor(id));
    }

    @PostMapping("confirmGroupInvoiceReceive")
    @ApiOperation(value = "组别发票，确认收到")
    public ApiResult<Boolean> confirmGroupInvoiceReceive(@RequestParam("id") Long id) {
        return ApiResult.ok(service.confirmGroupInvoiceReceive(id));
    }

    @ApiModelProperty("保存附件")
    @PostMapping("uploadAppendix")
    public ApiResult<Boolean> uploadAppendix(@RequestBody List<BillSaleAppendix> appendixList) {
        return ApiResult.ok(service.uploadAppendix(appendixList));
    }

    @ApiModelProperty("根据销售单ID获取路径")
    @GetMapping("getAppendixListById")
    public ApiResult<BillSaleAppendix> getAppendixListById(@RequestParam("id") Long id) {
        return ApiResult.ok(service.getAppendixListById(id));
    }

    @GetMapping("list_by_user_id")
    @ApiOperation(value = "根据用户维护客户拉取销售单 仅仅查询普通类型的销售单")
    public ApiResult<List<BillSaleVO>> list_by_user_id(@RequestParam(value = "reimburse_id", required = false) Long reimburse_id) {
        List<BillSaleVO> voList = service.list_by_user_id(reimburse_id);
        return ApiResult.ok(voList);
    }

    @GetMapping("get_customer_commission_by_sale_id")
    @ApiOperation(value = "根据销售单id 获取客提信息")
    public ApiResult<CustomerCommissionVO> get_customer_commission_by_sale_id(
            @RequestParam(value = "id") Long id,
            @RequestParam(value = "amount", required = false) BigDecimal amount) {
        CustomerCommissionVO vo = service.get_customer_commission_by_sale_id(id, amount);
        return ApiResult.ok(vo);
    }

    @PostMapping("/relation")
    @ApiOperation(value = "新建分组")
    public ApiResult<Boolean> relation(@RequestBody BillSaleGroupDTO dto) {
        return ApiResult.ok(service.relation(dto, ThreadLocalUserUtil.get().getId()));
    }

    @GetMapping("/list_group")
    @ApiOperation(value = "分组列表(用于搜索)")
    public ApiResult<List<BillSaleGroupVO>> listGroup() {
        return ApiResult.ok(service.listGroup(ThreadLocalUserUtil.get().getId()));
    }


    /*==========================================NEW ADD========================================*/
    @PostMapping("save-new")
    @ApiOperation("保存")
    public ApiResult<Boolean> save(@ApiParam("json") @RequestBody SaleBillDTO req) {
        try {
            Long saleBillId = service.save(req);
            if ( saleBillId > 0) {
                JSONObject obj = new JSONObject();
                obj.put("sale_bill_id",saleBillId);
                return ApiResult.ok(obj);
            } else {
                return ApiResult.err("保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.err(e.getMessage());
        }
    }

    @PutMapping("begin-new")
    @ApiOperation("提交")
    public ApiResult<Boolean> begin(@ApiParam("json") @RequestBody SaleBillDTO req) {
        try {
            Long saleBillId = service.begin(req);
            if ( saleBillId > 0) {
                JSONObject obj = new JSONObject();
                obj.put("sale_bill_id",saleBillId);
                return ApiResult.ok(obj);
            } else {
                return ApiResult.err("提交失败");
            }
        } catch (Exception e) {
            return ApiResult.err(e.getMessage());
        }
    }

    @GetMapping("detail-new")
    @ApiOperation(value = "单据明细")
    public ApiResult<SaleBillVO> detailNew(
            @ApiParam("id") @RequestParam(value = "id", required = false) Long id) {
        return ApiResult.ok(service.getSingleById(id));
    }

    @GetMapping("list-new")
    @ApiOperation(value = "列表分页")
    public ApiResult<Page<SaleBillVO>> listNew(@ApiParam("form") SaleBillListDTO req) {
        if (req.isManager()) {
            req.setUserId(null);
        } else {
            req.setUserId(ThreadLocalUserUtil.get().getId());
        }
        Page<SaleBillVO> BillSaleVOPage = service.selectNewPageList(req);
        return ApiResult.ok(BillSaleVOPage);
    }

    @GetMapping("list-page")
    @ApiOperation(value = "列表分页")
    public ApiResult<Page<BillSaleVO>> listPage(@ApiParam("form") BillSaleListDTO req) {
        if (req.isManager()) {
            req.setUserId(null);
        } else {
            req.setUserId(ThreadLocalUserUtil.get().getId());
        }
        Page<BillSaleVO> BillSaleVOPage = service.selectPageList(req);
        return ApiResult.ok(BillSaleVOPage);
    }

    @GetMapping("list-latest-sale-bill")
    @ApiOperation(value = "查询全部销售单(For市场单)")
    public ApiResult<List<SaleBillVO>> listLatestSaleBill(@Param("deptId") Long deptId,
                                                          @Param("contractId") Long contractId,
                                                          @Param("mustIncludeBillSaleId") Long mustIncludeBillSaleId,
                                                          @Param("type") Integer type) {
        List<SaleBillVO> saleBillList = service.listLatestSaleBill(deptId, contractId, mustIncludeBillSaleId, type);
        return ApiResult.ok(saleBillList);
    }

}
